// pages/admin/userList/userList.js
//获取应用实例
const app = getApp()

const config = require("../../../config.js");
const util = require("../../../utils/util");
const db = wx.cloud.database();
const _ = db.command;
const db_users = db.collection('user');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    usersList: [],
    userInfo: {},
    id: '',
    user: {},
    nomore: false,
    page: 0,
    fileUrl: '',
    departmentList: JSON.parse(config.data).departments,
    statusList: JSON.parse(config.data).status,
    departmentIndex: null,
    statusIndex: null,
  },
  statusChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value
    this.setData({
      statusIndex: e.detail.value
    })
    db_users.doc(this.data.id).update({
      data: {
        status: this.data.statusList[index],
        type: index,
      }
    }).then(res => {
      if (res.stats.updated == 1) {
        wx.showToast({
          title: '设置成功',
        })
      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: '操作请求异常',
        icon:'none'
      })
    })
  },
  departmentChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      departmentIndex: e.detail.value
    })
  },

  showModal(e) {
    let id = e.currentTarget.dataset.id
    this.setData({
      modalName: e.currentTarget.dataset.target,
      id: id
    })
    this.getuser(id)
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      id: ''
    })
    this.getUser()
  },
  editUser() {
    console.log('修改用户信息')
  },

  getuser(id) {
    db_users.doc(id).get({
      success: res => {
        console.log(res)
        this.setData({
          user: res.data,
          statusIndex: res.data.type
        })
      },
      fail: err => {
        console.error(err)
      }
    })
  },
  goDownload() {
    wx.navigateTo({
      url: '../../download/download?fileUrl=' + this.data.fileUrl,
    })
  },

  //获取fileurl
  getFileUrl(fileId) {
    let that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        // get temp file URL
        console.log("文件下载链接", res.fileList[0].tempFileURL)
        that.setData({
          fileUrl: res.fileList[0].tempFileURL
        })
      },
      fail: err => {
        // handle error
        console.error(err)
      }
    })
  },

  //exportOrder 导出数据
  async exportUser(params) {
    let that = this
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    });
    console.log('exportUser 导出数据')
    await wx.cloud.callFunction({
      name: 'user',
      data: {
        "action": "exportUser",
        "userList": that.data.usersList
      },
      success: res => {
        console.log("保存成功", res)
        // this.getFileUrl(res.result.fileID)
        wx.cloud.getTempFileURL({
          fileList: [res.result.fileID],
          success: res => {
            // get temp file URL
            console.log("文件下载链接", res.fileList[0].tempFileURL)
            that.setData({
              fileUrl: res.fileList[0].tempFileURL
            })
            wx.hideToast();
            that.goDownload()
          },
          fail: err => {
            // handle error
            console.error(err)
          }
        })
      },
      fail: err => {
        console.error("保存失败", err)
      }
    })
  },

  //加载更多
  more() {
    console.log('加载更多')
    let that = this;
    let page = that.data.page + 1;
    if (that.data.nomore || that.data.usersList.length < 100) {
      return false
    }
    db_users.orderBy('department', 'desc').skip((page - 1) * 20 + 100).limit(20).get({
      success: res => {
        console.log(res)
        if (res.data.length == 0) {
          that.setData({
            nomore: true
          })
          return false;
        }
        if (res.data.length < 20) {
          that.setData({
            nomore: true
          })
        }
        this.setData({
          page: page,
          userList: that.data.usersList.concat(res.data)
        })

      },
      fail: err => {
        wx.showToast({
          title: '获取失败',
          icon: 'none'
        })
      }
    })

  },
  // 云函数调用
  async getUser(page, pageSize, department) {
    let data = {}
    let that = this

    if (that.data.userInfo.type == 3) {
      data = {
        action: "getUser",
        page: page == null ? 0 : page,
        pageSize: pageSize == null ? 100 : pageSize
      }
    } else if (that.data.userInfo.type == 2) {
      data = {
        action: "getUser",
        department: this.data.userInfo.department,
        page: page == null ? 0 : page,
        pageSize: pageSize == null ? 100 : pageSize
      }
    }

    await wx.cloud.callFunction({
        name: 'user',
        data: data,
        // success: res => {
        //   console.log(res)
        //   console.log(res.result.list)
        //   this.setData({
        //     orderList: res.result.list
        //   })
        // },
        // fail: err => {
        //   console.error(err)
        // }
      })
      .then(res => {
        console.log(res) // 3
        console.log(res.result.data)
        if (res.result.data.length > 0) {
          this.setData({
            usersList: res.result.data
          })
          wx.stopPullDownRefresh()
        } else {
          this.setData({
            nomore: true
          })
        }
      })
      .catch(console.error)
  },

  //获取用户列表-小程序端
  getList() {
    db_users.get({
      success: res => {
        console.log(res)
        this.setData({
          usersList: res.data
        })
      },
      fail: err => {
        console.error(err)
      }
    })
  },
  //审核
  pass(e) {
    let id = e.currentTarget.dataset.id;
    console.log(id)
    db_users.doc(id).update({
      data: {
        status: '普通用户',
        type: '1'
      },
      success: res => {
        if (res.stats.updated == 1) {
          wx.showToast({
            title: '审核通过',
          });
          this.getUser();
        } else {
          wx.showToast({
            title: '审核失败',
            icon: 'none'
          });
        }

      },
      fail: err => {
        wx.showToast({
          title: '审核失败',
        })
      }
    })
  },
  //删除用户
  delUser(e) {

    let id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: res => {
        if (res.confirm) {
          db_users.doc(id).remove({
            success: res => {
              if (res.stats.removed == 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'none'
                });
                this.setData({
                  modalName: null,
                  id: ''
                })
                this.getUser();
              } else {
                wx.showToast({
                  title: '删除失败!',
                  icon: 'none'
                })
              }

            },
            fail: err => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  goUserEdit(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../../pages/userEdit/userEdit?id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // this.getUsersList();
    // this.getUser()
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUser()
    // this.getList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getUser();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.more();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})